package hmvictor.jpql;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.filesystems.FileChooserBuilder;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.WindowManager;

@ActionID(
        category = "File",
        id = "hmvictor.jpql.NewAction"
)
@ActionRegistration(
        displayName = "#CTL_NewAction"
)
@ActionReference(path = "Menu/File", position = 1100)
@Messages("CTL_NewAction=New")
public final class NewAction implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            JPQLEditorTopComponent editor=(JPQLEditorTopComponent) WindowManager.getDefault().findTopComponent("JQPLEditorTopComponent");
            boolean cancelled=false;
            if(editor.isThereUnsavedContent()) {
                NotifyDescriptor.Confirmation msg = new NotifyDescriptor.Confirmation("There are unsaved content. Do you want to save it first?", NotifyDescriptor.YES_NO_CANCEL_OPTION,
                        NotifyDescriptor.QUESTION_MESSAGE
                );
                Object result = DialogDisplayer.getDefault().notify(msg);
                if (NotifyDescriptor.YES_OPTION.equals(result)) {
                    File file=editor.getFile();
                    if(file == null) {
                        File home = new File(System.getProperty("user.home"));
                        file = new FileChooserBuilder("user-dir").setTitle("Save File").setDefaultWorkingDirectory(home).setApproveText("Save").showSaveDialog();
                    }
                    if(file != null) {
                        editor.saveContent(file);
                    }else{
                        cancelled=true;
                    }
                }else if(NotifyDescriptor.CANCEL_OPTION.equals(result)) {
                    cancelled=true;
                }
            }
            if(!cancelled) {
                editor.setNewContent();
            }
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    
}
